/**
 * Created with JetBrains PhpStorm.
 * User: vander
 * Date: 4/23/13
 * Time: 8:23 PM
 * To change this template use File | Settings | File Templates.
 */
var MyBook = Class.create({
    initialize: function(o){
        // o {name, containerId}
        var _this = this;

        this.idPrefix = parseInt(new Date().getTime() / 1000);
        this.name = o.name;
        this.id = this.idPrefix;
        this.coverImage = "";

        this.divTag = new Element("ul", {id: this.id});

        this.pages = new Array();
        //Dung de cap phat Id
        this.pageIdFeed = 0;

        $(this.divTag).update(
            "<li id='add-new-page'>" +
                "<div class='item'>" +
                    "<img src='img/icons/addPage.png'>" +
                "</div><p class='subtitle'>Add Page</p>" +
            "</li>"
        );

        ///Xu ly su kien click vao item page preview
        $j(this.divTag).on("click", "li.child", function(){
            if(Global.currentPage != null){
                if(Global.currentPage.id != $j(this).attr("pageId")){
                    $j(Global.currentPage.divTag).css("display", "none");

                    //Xoa lua chon page ben page-preview va chon vao cai moi
                    $j(_this.divTag).find("li.selected").removeClass("selected");
                    $j(this).addClass("selected");

                    //Hien thi MyPage moi chon len
                    var pageId = $j(this).attr("pageId");
                    $j("#"+pageId).css("display", "block");

                    //Set lai MyPage moi vao bien global
                    Global.currentPage = _this.getPageById(pageId);

                    //Clear PropertyEditor
                    Global.propertyEditor.clear();

                    //Load ElementsView
                    Global.elementsView.load(Global.currentPage);

                    if(Global.currentSelectedEle != null){
                        $j("#" + Global.currentSelectedEle).removeClass("resource-selected");
                        Global.currentSelectedEle = null;
                    }
                }
            }
            else{
                $j(this).addClass("selected");

                //Hien thi MyPage moi chon len
                var pageId = $j(this).attr("pageId");
                $j("#"+pageId).css("display", "block");

                //Set lai MyPage moi vao bien global
                Global.currentPage = _this.getPageById(pageId);

                //Clear PropertyEditor
                Global.propertyEditor.clear();

                //Load ElementsView
                Global.elementsView.load(Global.currentPage);

                if(Global.currentSelectedEle != null){
                    $j("#" + Global.currentSelectedEle).removeClass("resource-selected");
                    Global.currentSelectedEle = null;
                }
            }
        });

        //Hien dau delete moi khi hover qua
        $j(this.divTag).on(
            {
                mouseenter: function(){
                    $j(this).find("img.delete").css("visibility", "visible" );
                },
                mouseleave: function(){
                    $j(this).find("img.delete").css("visibility", "hidden" );
                }
            }, "li.child"
        );

        //Xu ly su kien click vao dau delete
        $j(this.divTag).on("click", "li.child img.delete", function(){
            var li = this;
            $j("#" + Static.dialogConfirmDeletePage).dialog({
                autoOpen: true,
                modal: true,
                show: true,
                hide: true,
                resizable: false,
                buttons: {
                    "Yes": function(){

                        $j("#" + Static.dialogConfirmDeletePage).dialog("destroy");
                        _this.removePage($j(li).parent());
                    },
                    "No": function(){
                        $j("#" + Static.dialogConfirmDeletePage).dialog("destroy");
                    }
                }
            });
        });

        $j("#"+Static.containerPagePreview).empty().append(this.divTag);

        $j("#add-new-page").on("click", function(event){
            _this.createNewPage("end");
        });
    },
    createNewPage: function(type){
        Global.undoRedo.pushUndoStack("ADD_PAGE", this.toJSON());
        //type : before || after || end of currentPage
        var _this = this;

        //MyBook->lay id de gan cho new MyPage
        var newId = _this.getNewPageId();
        //Khoi tao li tag de insert vao cot preview
        var liTag = new Element("li", {pageId: newId, class: "child"});
        $j(liTag).html(
            "<img src='img/icons/delete-icon-small.png' class='delete' style='width: 16px; height:16px; right: 4px;top: 4px; position: absolute; visibility: hidden'>"+
            "<div class='item'>" +
            "</div>" +
            "<p class='subtitle'>" + newId + "</p>"
        );
        ///Them li vao trong danh sach pages preview
        if(type == "end"){
            $j(_this.divTag).append(liTag);
        } else if(type == "before"){
            if(Global.currentPage != null){
                $j(_this.divTag).find("li[pageId=" + Global.currentPage.id + "]").before(liTag);
            }
        } else if(type == "after"){
            if(Global.currentPage != null){
                $j(_this.divTag).find("li[pageId=" + Global.currentPage.id + "]").after(liTag);
            }
        }

        //Xoa lua chon page ben page-preview va chon vao cai moi tao.
        $j(_this.divTag).find("li.selected").removeClass("selected");
        $j(liTag).addClass("selected");

        //Khoi tao MyPage
        var newPage = new MyPage({
            id: newId,
            book: _this
        });


        _this.addPage(newPage, type);

        //Gan MyPage cho currentPage
        if(Global.currentPage != null){
            $j(Global.currentPage.divTag).css("display", "none");
        }

        Global.currentPage = newPage;
        $j(Global.currentPage.divTag).css("display", "block");

        //Clear PropertyEditor
        Global.propertyEditor.clear();

        //Load ElementsView
        Global.elementsView.load(newPage);

        if(Global.currentSelectedEle != null){
            $j("#" + Global.currentSelectedEle).removeClass("resource-selected");
            Global.currentSelectedEle = null;
        }


    },
    getNewPageId: function(){
//        return this.id + "-page" + this.pageIdFeed++;
        return "page" + this.pageIdFeed++;
    },
    addPage: function(p, type){
        if(type == "end"){
            this.pages.push(p);
        }
        else {
            var newArray = new Array();
            for(var i = 0, j = 0 ; i < this.pages.length + 1; i++){
                if(this.pages[j].id != Global.currentPage.id){
                    newArray[i] = this.pages[j];
                    j++;
                }
                else {
                    if(type == "before"){
                        newArray[i] = p;
                        i++;
                        newArray[i] = this.pages[j];
                    }
                    else if(type == "after"){
                        newArray[i] = this.pages[j];
                        i++;
                        newArray[i] = p;
                    }
                    j++;
                }
            }

            this.pages = newArray;
        }
    },
    removePage: function(liTag){
        Global.undoRedo.pushUndoStack("REMOVE_PAGE", this.toJSON());

        //Chay hieu ung xoa
        $j(liTag).effect("clip", "normal", function(){
            //Xoa list item
            $j(liTag).remove();
        });

        //Xoa view va xoa page khoi book
        var pageId = $j(liTag).attr("pageId");
        for(var i = 0 ;i < this.pages.length ; i++){
            if(this.pages[i].id == pageId){
                this.pages[i] = null;
                break;
            }
        }
        this.pages = this.pages.compact();
        //Xoa view
        $j("#"+pageId).remove();

        //Xoa title neu la page hien tai dong thoi gan lai currentPage la null
        if(Global.currentPage.id == pageId){
            Global.currentPage = null;
        }
        //Clear PropertyEditor
        Global.propertyEditor.clear();

        //Clear ElementsView
        Global.elementsView.clear();

        //Xoa selectedElement
        if(Global.currentSelectedEle != null){
            $j("#" + Global.currentSelectedEle).removeClass("resource-selected");
            Global.currentSelectedEle = null;
        }
    },
    removePageById: function(pageId){
        var liTag = $j(this.divTag).find("li[pageId=" + pageId + "]");
        this.removePage(liTag);
    },
    getPageById: function(id){
        for (var i = 0 ; i < this.pages.length ; i++){
            if(this.pages[i].id == id){
                return this.pages[i];
            }
        }
        return null;
    },
    toJSON: function(){
        var book = new Object();
        book['name'] = this.name;
        book['id'] = this.id;
        book['coverImage'] = this.coverImage.replace(Static.uploaderPath, "");
        book['pageIdFeed'] = this.pageIdFeed;
        book['pages'] = new Array();

        $j.each(this.pages, function(index, value){
            book['pages'].push(value.toJSON());
        });

        return book;
    },
    fromJSON: function(o){
        this.name = o.name;
        this.id = o.id;
        this.coverImage = Static.uploaderPath + o.coverImage;
        this.pageIdFeed = o.pageIdFeed;
        this.pages = new Array();
        var _this = this;

        $j.each(o.pages, function(index, value){
            //Khoi tao li tag de insert vao cot preview
            var liTag = new Element("li", {pageId: value.id, class: "child"});
            $j(liTag).html(
                "<img src='img/icons/delete-icon-small.png' class='delete' style='width: 16px; height:16px; right: 4px;top: 4px; position: absolute; visibility: hidden'>"+
                    "<div class='item'>" +
                    "</div>" +
                    "<p class='subtitle'>" + value.id + "</p>"
            );
            ///Them li vao trong danh sach pages preview
            $j(_this.divTag).append(liTag);

            //Khoi tao MyPage
            var newPage = new MyPage({
                id: value.id,
                book: _this
            });
            newPage.fromJSON(value);

            _this.addPage(newPage, "end");

            //View thumbnail phu hop cho page vua them vao
            MyTools.viewThumbnail(value.id);
        });

    },
    destroy: function(){
        $j(this.divTag).remove();
        for(var i = 0; i < this.pages.length; i++){
            this.pages[i].destroy();
        }


        //Clear PropertyEditor
        Global.propertyEditor.clear();

        //Clear ElementsView
        Global.elementsView.clear();

        Global.currentSelectedEle = null;
        Global.currentPage = null;
        Global.currentBook = null;
    }
});